package com.ihr360.job.core.repeat.policy;

import com.ihr360.job.core.repeat.CompletionPolicy;
import com.ihr360.job.core.repeat.RepeatContext;
import com.ihr360.job.core.repeat.RepeatStatus;
import com.ihr360.job.core.repeat.context.RepeatContextSupport;

/**
 * Very simple base class for {@link CompletionPolicy} implementations.
 *
 * @author Dave Syer
 *
 */
public class CompletionPolicySupport implements CompletionPolicy {

    /**
     * If exit status is not continuable return <code>true</code>, otherwise
     * delegate to {@link #isComplete(RepeatContext)}.
     *
     * @see com.ihr360.job.core.repeat.CompletionPolicy#isComplete(com.ihr360.job.core.repeat.RepeatContext,
     * RepeatStatus)
     */
    @Override
    public boolean isComplete(RepeatContext context, RepeatStatus result) {
        if (result != null && !result.isContinuable()) {
            return true;
        }
        else {
            return isComplete(context);
        }
    }

    /**
     * Always true.
     *
     * @see com.ihr360.job.core.repeat.CompletionPolicy#isComplete(com.ihr360.job.core.repeat.context.RepeatContext)
     */
    @Override
    public boolean isComplete(RepeatContext context) {
        return true;
    }

    /**
     * Build a new {@link RepeatContextSupport} and return it.
     *
     * @see com.ihr360.job.core.repeat.CompletionPolicy#start(RepeatContext)
     */
    @Override
    public RepeatContext start(RepeatContext context) {
        return new RepeatContextSupport(context);
    }

    /**
     * Increment the context so the counter is up to date. Do nothing else.
     *
     * @see com.ihr360.job.core.repeat.CompletionPolicy#update(com.ihr360.job.core.repeat.RepeatContext)
     */
    @Override
    public void update(RepeatContext context) {
        if (context instanceof RepeatContextSupport) {
            ((RepeatContextSupport) context).increment();
        }
    }

}
